package org.example.auth.controller;

import org.example.auth.domain.Oauth2TokenDto;
import org.example.common.base.constants.AuthConstant;
import org.example.common.base.util.web.AjaxResult;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0.0
 * @className: AuthController
 * @description: 自定义Oauth2获取令牌接口
 * @author: LiJunYi
 * @create: 2023/4/3 17:04
 */
@RestController
@RequestMapping("/oauth")
public class AuthController {

    private final TokenEndpoint tokenEndpoint;

    public AuthController(TokenEndpoint tokenEndpoint) {
        this.tokenEndpoint = tokenEndpoint;
    }

    /**
     * Oauth2获取token
     *
     * @param request       请求
     * @param grant_type    授权模式
     * @param client_id     Oauth2客户端ID
     * @param client_secret Oauth2客户端秘钥
     * @param refresh_token 刷新token
     * @param username      用户名
     * @param password      密码
     * @return {@link AjaxResult}
     * @throws HttpRequestMethodNotSupportedException http请求方法不支持异常
     */
    @PostMapping("/token")
    public AjaxResult postAccessToken(HttpServletRequest request, @RequestParam String grant_type,
                                      @RequestParam String client_id, @RequestParam String client_secret,
                                      @RequestParam(required = false) String refresh_token, @RequestParam(required = false) String username,
                                      @RequestParam(required = false) String password) throws HttpRequestMethodNotSupportedException {
        Map<String, String> parameters = new HashMap<>();
        parameters.put("grant_type",grant_type);
        parameters.put("client_id",client_id);
        parameters.put("client_secret",client_secret);
        parameters.putIfAbsent("refresh_token",refresh_token);
        parameters.putIfAbsent("username",username);
        parameters.putIfAbsent("password",password);
        OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(request.getUserPrincipal(), parameters).getBody();
        assert oAuth2AccessToken != null;
        Oauth2TokenDto oauth2TokenDto = Oauth2TokenDto.builder()
                .token(oAuth2AccessToken.getValue())
                .refreshToken(oAuth2AccessToken.getRefreshToken().getValue())
                .expiresIn(oAuth2AccessToken.getExpiresIn())
                .tokenHead(AuthConstant.JWT_TOKEN_PREFIX).build();

        return AjaxResult.success(oauth2TokenDto);
    }
}
